<template>
  <div class="w-full h-full">
    <div class="flex justify-center">
      <div class="pt-10">
        <Card class="">
          <h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900">7天前的打卡记录</h5>
          <p class="font-normal text-gray-700 dark:text-gray-400">从今天算起，7天前的打卡记录</p>
          <el-divider/>
          <div class="flex justify-center" id="chartsContainer">
            <Line v-if="refreshCharts" :data="chartData" :options="chartOption" :width="chartWidth" id="charts"/>
          </div>
          <!--下拉菜单按钮-->
          <button @click="dropDownClick" data-dropdown-toggle="dropdown" class="mt-3 text-white bg-blue-700 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center inline-flex items-center" type="button">
            选择打卡人
            <svg class="w-2.5 h-2.5 ml-2.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 10 6">
            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 4 4 4-4"/>
          </svg></button>
          <span class="text-sm text-gray-500 pl-5">当前选择：{{curName}}</span>
          <!-- 下拉菜单 -->
          <div v-show="dropMenuVis" class="z-10 bg-white divide-y divide-gray-100 rounded-lg shadow w-44">
            <ul class="py-2 text-sm text-gray-700 " aria-labelledby="dropdownDefaultButton">
              <li v-for="name in nameList">
                <a class="block px-4 py-2" style="cursor:pointer;" @click="dropMenuItemClick(name)">{{name}}</a>
              </li>
            </ul>
          </div>
          <el-divider/>
          <p class="pt-1 text-sm">累计打卡<span class="font-bold">{{curCount}}</span>次</p>
        </Card>
        <Card class="mt-6">
          <div class="tableDiv" style="overflow-x: auto">
            <el-table :data="tableData" height="400" style="width: 100%;z-index: unset">
<!--              <el-table-column prop="userName" label="打卡人" width="80"/>-->
              <el-table-column prop="taskName" label="任务名" :width="isPhone ? '100' : '250'">
                <template #default="scope">
                  <el-popover
                      placement="bottom"
                      title="任务名"
                      :width="200"
                      trigger="click"
                      :content="scope.row.taskName"
                  >
                    <template #reference>
                      <span class="font-extrabold">{{isPhone && scope.row.taskName.length >= 4 ? scope.row.taskName.substring(0,4)+"..." : scope.row.taskName}}</span>
                    </template>
                  </el-popover>
<!--                  <span class="font-extrabold">{{scope.row.taskName.length >= 4 ? scope.row.taskName.substring(0,4)+"..." : scope.row.taskName}}</span>-->
                </template>
              </el-table-column>
              <el-table-column prop="createDate" label="打卡时间" :width="isPhone ? '110' : '250'">
                <template #default="scope">
                  {{scope.row.createDate.substring(0,10)}}
                </template>
              </el-table-column>
              <el-table-column prop="imgUrl" label="打卡图片" :width="isPhone ? '100' : '250'">
                <template #default="scope">
                  <el-image
                      style="width: 100px; height: 100px"
                      :src="scope.row.imgUrl"
                      :zoom-rate="1.2"
                      :preview-src-list="[scope.row.imgUrl]"
                      :initial-index="4"
                      fit="cover"
                  />
                  <!--                <img :src="scope.row.imgUrl"/>-->
                </template>
              </el-table-column>
            </el-table>
          </div>

        </Card>
      </div>
    </div>

  </div>
</template>

<script>
import Card from "../components/Main/Card.vue";
import {Line} from 'vue-chartjs'
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement
} from 'chart.js'
import {ElMessage} from "element-plus";
import {API} from "../utils/API.js";

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
)
export default {
  name: 'PersonalRecordView',
  components: {Card, Line},
  data() {
    return {
      isPhone: false,
      tableData:[],
      refreshCharts: true,
      curCount: 0,
      curName: '未选择',
      curDataList: [],
      nameList:[],
      dropMenuVis: false,
      chartData: {
        labels: [],
        datasets: [
          {
            label: '完成任务数量',
            backgroundColor: '#f87979',
            data: [],
          }
        ]
      },
      chartOption: {
        responsive: true,
        maintainAspectRatio: false,
        layout: {
          width: 2000,
          height: 500
        }
      },
      chartWidth: 0,
    }
  },
  methods: {
    doRefreshCharts(){
      this.refreshCharts = false;
      setTimeout(() => {
        this.refreshCharts = true;
      },0)
    },
    dropDownClick() {
      this.dropMenuVis = !this.dropMenuVis;
    },
    openMenu() {
      this.menuShow = !this.menuShow;
    },
    updateChartWidth() {
      const windowWidth = window.innerWidth;
      if (windowWidth <= 768) {
        // 手机设备
        this.chartWidth = 320;
        this.isPhone = true;
      } else {
        // 电脑设备
        this.chartWidth = 700;
      }
    },
    getNameList() {
      API.get('/task_record/getAllName')
          .then(res => {
            if (res && res.data && res.data.data) {
              const list = res.data.data.list;
              if (list) {
                this.nameList = list;
              }
            }
          })
    },
    async dropMenuItemClick(name) {
      const param = {
        "name": name
      }
      this.curName = name;
      await API.get('/task_record/getCountByName' , {params: param})
          .then(res => {
            const list = res.data.data.list;
            if (list) {
              this.curCount = list;
            }
          })
      await API.get('/task_record/getAllRecordByNameInWeek' , {params: param})
          .then(res => {
            if (res && res.data && res.data.data) {
              const list = res.data.data.list;
              if (list) {
                this.curDataList = list;
                let arr = [];
                let map = new Map();
                list.forEach(item => {
                  map.set(item.day, item.total_count);
                })
                this.chartData.labels.forEach(item => {
                  if (map.has(item)) {
                    arr.push(map.get(item));
                  } else {
                    arr.push(0);
                  }
                })
                this.chartData.datasets[0].data = arr;
              }
            }
          })
      this.dropMenuVis = false;
      console.log(JSON.stringify(this.chartData.datasets[0].data));
      this.doRefreshCharts();
      this.getByName(name);
    },
    getDatesFromTodayToLastWeek() { //获取数据
      const oneDayInMilliseconds = 24 * 60 * 60 * 1000; // One day in milliseconds
      const today = new Date(); // Current date
      const oneWeekAgo = new Date(today - 6 * oneDayInMilliseconds); // One week ago

      const datesArray = [];
      let currentDate = new Date(today); // Start from today

      while (currentDate >= oneWeekAgo) {
        const year = currentDate.getFullYear(); // Get the year
        const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Get the month and add leading zero if necessary
        const day = String(currentDate.getDate()).padStart(2, '0'); // Get the day and add leading zero if necessary
        const formattedDate = `${year}-${month}-${day}`;
        datesArray.push(formattedDate);

        currentDate = new Date(currentDate - oneDayInMilliseconds); // Subtract one day from the date
      }
      datesArray.reverse();
      this.chartData.labels = datesArray;
    },
    getByName(name) {
      const param = {
        "name": name
      }
      API.get('/task_record/getByName', {params: param})
          .then(res => {
            if (res && res.data && res.data.data) {
              const list = res.data.data.list;
              if (list) {
                this.tableData = list;
              }
            }
          })
    }
  },
  beforeMount() {
    this.getDatesFromTodayToLastWeek();
    this.getNameList();
    this.updateChartWidth();
  },
  mounted() {

  },
  beforeUnmount() {

  }
}
</script>

<style scoped>
@media (max-width: 640px) {
  .tableDiv{
    width: 320px;
  }
}
@media (min-width: 640px) {

}
</style>